﻿using LightCAD.MathLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace LightCAD.MathLib
{
    public class Polyline2d : Curve2d
    {
        private Box2 _boundingBox;

        public List<Curve2d> Curve2ds;
        public Vector2[] Points { get; set; }

        [JsonIgnore]
        public override bool IsClosed
        {
            get {
                if (Points == null || Points.Length < 3)
                {
                    return false;
                }
                return Points[0] == Points[Points.Length - 1];
            }
        }
        public Polyline2d()
        {
            this.Type = Curve2dType.Polygon2d;
            Points = new Vector2[] { };
        }
        public override void Copy(Curve2d src)
        {
            var polyline = src as Polyline2d;
            this.Points = polyline.Points.Clone<Vector2>();
            this.Name = polyline.Name;
        }
        public override Curve2d Clone()
        {
            var newObj = new Polyline2d();
            newObj.Copy(this);
            return newObj;
        }

        public void ResetBoundingBox()
        {
            _boundingBox = null;
        }

        public override Curve2d Translate(Vector2 offset)
        {
            for (int i = 0; i < this.Points.Length; i++)
            {
                var p = this.Points[i];
                p.Add(offset);
            }
            this._boundingBox?.Max.Add(offset);
            this._boundingBox?.Min.Add(offset);
            return this;
        }

        public override Curve2d RotateAround(Vector2 basePoint, double angle)
        {
            for (int i = 0; i < this.Points.Length; i++)
            {
                var p = this.Points[i];
                p.RotateAround(basePoint, angle);
            }
            this._boundingBox = null;
            return this;
        }

        public override Curve2d Mirror(Vector2 axisStart, Vector2 axisDir)
        {
            for (int i = 0; i < this.Points.Length; i++)
            {
                var p = this.Points[i];
                p.Mirror(axisStart, axisDir);
            }
            this._boundingBox = null;
            return this;
        }

        public Box2 BoundingBox
        {
            get
            {
                _boundingBox = new Box2();
                if (_boundingBox == null)
                {
                    _boundingBox.ExpandByPoints(Points);
                }
                return _boundingBox;
            }
        }
        public override Vector2[] GetPoints(int div = 5, double scaleInFuture = 1)
        {
            return Points.Select(p => p.Clone()).ToArray();
        }

    }
}
